package com.pro.common.modules.service.dependencies.service;

import com.pro.common.api.cursor.sync.service.ICursorSyncHandler;
import com.pro.framework.api.enums.ITaskCursorKey;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

@Slf4j
@AllArgsConstructor
@Getter
public class SqlExecuteCursorSyncHandler implements ICursorSyncHandler<Long, Long> {

    protected final JdbcTemplate jdbcTemplate;
    protected final ITaskCursorKey cursorKey;
    protected final String sql;
    protected final String updateTableName;
    private final Boolean cursorAscending = false;

    @Override
    public Class<Long> getCursorClass() {
        return Long.class;
    }

    @Override
    public Long getDefaultCursor() {
        return getMaxId();
    }

    @Override
    public Integer getBatchSize() {
        return 50000;
    }

    @Override
    public List<Long> fetchData(Long cursor, int limit, Long endIfNeed) {
//        // 检查终止条件
//        if (!getCursorAscending() && cursor <= getMinId()) {
//            log.info("[{}] 已处理到最小ID: {}, 任务完成", getCursorKey(), getMinId());
//            return List.of();
//        }
//        if (getCursorAscending() && cursor >= getMaxId()) {
//            log.info("[{}] 已处理到最大ID: {}, 任务完成", getCursorKey(), getMaxId());
//            return List.of();
//        }
        return List.of(cursor);
    }

    @Override
    public void process(List<Long> dataList) {
        if (dataList.isEmpty()) {
            return;
        }

        Long currentCursor = dataList.get(0);
        Long batchStart;
        Long batchEnd;

        if (getCursorAscending()) {
            // 升序: currentCursor 是起始ID
            batchStart = currentCursor;
            batchEnd = Math.min(currentCursor + getBatchSize() - 1, getMaxId());
        } else {
            // 降序: currentCursor 是结束ID
            batchEnd = currentCursor;
            batchStart = Math.max(currentCursor - getBatchSize() + 1, getMinId());
        }

        int updated = jdbcTemplate.update(sql, batchStart, batchEnd);
        log.warn("[{}] 批量更新 {} 条, ID范围 {}~{}", getCursorKey(), updated, batchStart, batchEnd);
    }

    @Override
    public Long extractCursorValue(Long item) {
        if (getCursorAscending()) {
            return item + getBatchSize();
        } else {
            return Math.max(item - getBatchSize(), getMinId());
        }
    }

    protected Long getMaxId() {
        String maxSql = "SELECT MAX(id) FROM " + updateTableName;
        Long maxId = jdbcTemplate.queryForObject(maxSql, Long.class);
        return maxId != null ? maxId : 0L;
    }

    protected Long getMinId() {
        return 0L;
//        String minSql = "SELECT MIN(id) FROM " + updateTableName;
//        Long minId = jdbcTemplate.queryForObject(minSql, Long.class);
//        return minId != null ? minId : 0L;
    }
}